package demoMod.stsconsole.saves;

import com.google.gson.JsonElement;
import demoMod.stsconsole.annotations.DataSaver;
import demoMod.stsconsole.cards.AbstractCard;
import demoMod.stsconsole.interfaces.CustomSavable;

import java.util.HashMap;
import java.util.Map;

public abstract class InstanceDataSaver<I extends CustomSavable<T>, T> {
    private static final Map<Class<?>, InstanceDataSaver<?, ?>> dataSaverMap = new HashMap<>();

    public InstanceDataSaver() {
    }

    public T onSave(I instanceToSave) {
        return instanceToSave.onSave();
    }

    public JsonElement onSaveRaw(I instanceToSave) {
        return CustomSavable.saveFileGson.toJsonTree(onSave(instanceToSave));
    }

    public void onLoad(I instanceToLoad, T data) {
        instanceToLoad.onLoad(data);
    }

    public void onLoadRaw(I instanceToLoad, JsonElement data) {
        if (data != null) {
            T parsed = CustomSavable.saveFileGson.fromJson(data, instanceToLoad.savedType());
            onLoad(instanceToLoad, parsed);
        } else {
            onLoad(instanceToLoad, null);
        }
    }

    public static InstanceDataSaver getSaver(Class<?> cls) {
        if (dataSaverMap.containsKey(cls)) {
            return dataSaverMap.get(cls);
        }
        if (cls.isAnnotationPresent(DataSaver.class)) {
            DataSaver dataSaver = cls.getAnnotation(DataSaver.class);
            try {
                dataSaverMap.put(cls, dataSaver.cls().newInstance());
                return dataSaverMap.get(cls);
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        } else if (!cls.getName().equals("java.lang.Object")) {
            return getSaver(cls.getSuperclass());
        }
        return dataSaverMap.get(AbstractCard.class);
    }
}
